package Texas;


import java.util.ArrayList;

import Texas.Card.Card;


public class Showdown {
	
	private Table _table;
	private ArrayList<Player> _players;
	private Player _winner;
	
	public Showdown(Table table, ArrayList<Player> players) {
		_table = table;
		_players = players;
		_winner = null;
	}
	
	public void start() {
		float score = 0, currentHiScore = 0;
		Player player;
		PlayerIterator playerIterator = new PlayerIterator(_players, _table.getDealerButton());
		HandChecker handChecker = new HandChecker();
		
		while(playerIterator.hasNext()) {
			ArrayList<Card> cards = new ArrayList<Card>();
			player = playerIterator.next();
			
			cards.addAll(player.getCards());
			cards.addAll(_table.getCommunityCards());
			sortCards(cards);
			
			for(int i = 0; i < 8; i++) {
				switch(i) {
				case 0: score = handChecker.hasRoyalFlush(cards); break;
				case 1: score = handChecker.hasFourOfAKind(cards); break;
				case 2: score = handChecker.hasFullHouse(cards); break;
				case 3: score = handChecker.hasFlush(cards); break;
				case 4: score = handChecker.hasStreet(cards); break;
				case 5: score = handChecker.hasThreeOfAKind(cards); break;
				case 6: score = handChecker.hasTwoPair(cards); break;
				case 7: score = handChecker.hasOnePair(cards); break;
				}

				if(score != 0) {
					break;
				}
			}
			
			score += getHiCardOfPocketCards(player)/1000;
			
			System.out.println("SCORE: "+ currentHiScore);
			
			if(currentHiScore == 0 && _winner == null) {
				currentHiScore = score;
				_winner = player;
			} else {
				if(currentHiScore < score) {
					currentHiScore = score;
					_winner = player;
				}
			}
		}
	}
	
	private void sortCards(ArrayList<Card> cards) {
		Card temp;
		for(int i = 0; i < cards.size(); i++){
			for(int j = i+1; j < cards.size(); j++) {
				if(cards.get(j).getRank().getValue() > cards.get(i).getRank().getValue()) {
					temp = cards.get(j);
					cards.remove(j);
					cards.add(i, temp);
				}
			}
		}
	}
	
	private int getHiCardOfPocketCards(Player player) {
		if(player.getCard(0).getRank().getValue() >= player.getCard(1).getRank().getValue())
			return player.getCard(0).getRank().getValue()+player.getCard(0).getSuit().getValue();
		else
			return player.getCard(1).getRank().getValue()+player.getCard(1).getSuit().getValue();
	}
	
	public Player getWinner() {
		return _winner;
	}
}
